package org.t236.web;


import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.t236.commons.model.AjaxResult;
import org.t236.commons.model.User;
import org.t236.dubbo.user.UserServiceDubboApi;
import org.t236.feign.order.OrderRemoteClient;
import org.t236.feign.user.UserRemoteClient;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 消费者项目
 */
@SpringBootApplication(scanBasePackages = {"org.t236.web", "org.t236.feign"})
@RestController
@EnableFeignClients(basePackages = "org.t236.feign")
@EnableDiscoveryClient
public class MallApp {
    @Resource
    private OrderRemoteClient orderRemoteClient;
    @Resource
    private UserRemoteClient userRemoteClient;

    @DubboReference(timeout = 1000, mock = "org.t236.dubbo.user.UserServiceDubboApiMock")
    private UserServiceDubboApi userServiceDubboApi;

    @GetMapping("/helloDubbo")
    public AjaxResult hello(String name) {
        return AjaxResult.success(userServiceDubboApi.hello(name));
    }

    @PostMapping("/addUser")
    public AjaxResult postAdd( User user) {
        return userRemoteClient.add(user);
    }

    @GetMapping
    public AjaxResult hello(Long userId) {
        AjaxResult orderResult = orderRemoteClient.findByUserId(userId);
        AjaxResult userResult = userRemoteClient.find(userId);
        Map<String, Object> map = new HashMap<>();
        if(orderResult.getCode() != AjaxResult.SUCCESS) {
            map.put("orders", orderResult.getMsg());
        } else {
            map.put("orders", orderResult.getData());
        }
        if(userResult.getCode() != AjaxResult.SUCCESS) {
            map.put("users", userResult.getMsg());
        } else {
            map.put("users", userResult.getData());
        }
        return AjaxResult.success(map);
    }


    public static void main(String[] args) {
        SpringApplication.run(MallApp.class, args);
    }
}
